#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
#         http://binux.me
# Created on 2012-10-24 16:08:17

import logging
import sys

try:
    import curses
except ImportError:
    curses = None


class LogFormatter(logging.Formatter, object):
    """Init tornado.log.LogFormatter from logging.config.fileConfig"""
    def __init__(self, fmt=None, datefmt=None, color=True, *args, **kwargs):
        if fmt is None:
            fmt = "[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] %(message)s"
        super(LogFormatter, self).__init__(fmt=fmt, *args, **kwargs)

log_file = None

class LogHandler(logging.FileHandler):

    def __init__(self):
        if  log_file is None:
            logging.StreamHandler.__init__(self, sys.stderr)
        elif isinstance(log_file, file):
            logging.StreamHandler.__init__(self, log_file)
        else:
            logging.FileHandler.__init__(self, log_file)


class SaveLogHandler(logging.Handler):
    """LogHandler that save records to a list"""

    def __init__(self, saveto=None, *args, **kwargs):
        self.saveto = saveto
        logging.Handler.__init__(self, *args, **kwargs)

    def emit(self, record):
        if self.saveto is not None:
            self.saveto.append(record)

    handle = emit


def enable_pretty_logging(logger=logging.getLogger()):
    channel = logging.StreamHandler()
    channel.setFormatter(LogFormatter())
    logger.addHandler(channel)
